module.exports = {

    checkToken: checkToken,

    wxlogin: wxlogin,
    bindPhone: bindPhone,
    login: login,

    uploadFile: uploadFile,

    saveUi: saveUi,
    findUiByPager: findUiByPager,
    getUiReport:getUiReport,
    getNewUiRet:getNewUiRet,
    exPortUis: exPortUis,


    getCode: getCode,

    findAllInfos: findAllInfos,
    addFriend: addFriend,
    updInfo: updInfo,
    delFriend: delFriend,

}


var app = getApp()


var apiHost = app.globalData.api_host;

var apiHost = "https://emp.empsun.com";
// var apiHost = "https://empsun.empsun.com";

// 登录地址, 根据这个地址来设置token
var logInUrl = "/Account/LogInForMiniProgram";
// 例外不用token的地址
var exceptionAddrArr = [
    'http://localhost:8080',

];

function hasToken() {
    if (app.globalData.head.token == null || app.globalData.head.token == "") {
        return false;
    } else {
        return true;
    }

}


//登录接口，给与回调，同步执行代码
function wxlogin(eData, iv) {
    return new Promise(function (resolve, reject) {
        wx.pro.login().then(res => {
            app.log("用户的code====>>>" + res.code);
            wxLogin(res.code, eData, iv).then(res => {
                app.log('==>>wxlogin：请求调用成功')
                // 获取到用户的 openid
                app.log("用户的openid:" + res.data.data.openid);

                app.globalData.head.openid = res.data.data.openid
                // app.globalData.head.token = 'no'

                app.log(app.globalData)
                // app.log(app.globalData.tokenkey)

                checkStatus(res)
                //请求成功回调
                resolve(res.data.data)
            }).catch(err => {
                app.log('==>>wxlogin：请求调用失败')
                //请求失败回调
                reject(err)
            })

        }).catch(err => {
            app.log('==>>获取code失败')
        })
    })

}

//将用户授权后获取到的手机号上传到服务器并绑定到openid
function bindPhone(data) {
    let uri = '/s-xcx/api/v3/wx/bindPhone'
    data.openid = app.globalData.head.openid
    return new Promise(function (resolve, reject) {
        post(uri, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

function wxLogin(code, data, iv) {
    let uri = '/s-xcx/api/v3/wx/wxLogin?type=UI&code=' + URLencode(code) + '&eData=' + URLencode(data) + '&iv=' + URLencode(iv)
    return new Promise(function (resolve, reject) {
        get(uri).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

function login() {
    let uri = '/s-xcx/api/v3/wx/login?openid=' + app.globalData.head.openid
    return new Promise(function (resolve, reject) {
        get(uri).then(res => {
            app.log('==>>login res')
            app.globalData.head.token = res.data.data.token
            app.globalData.head.hasToken = true
            app.globalData.users = res.data.data.infos
            app.globalData.userId = res.data.data.userId

            resolve(res)
        }).catch(err => {
            app.log('==>>login err')
            reject(err)
        })
    })


}

function uploadFile(filePath) {
    let uri = '/s-file/api/file/uploads'
    return new Promise(function (resolve, reject) {
        getHeader(uri).then(res => {
            wx.pro.uploadFile({
                header: res,
                url: apiHost + uri,
                filePath: filePath,
                name: 'multipartFile',
                formData: {
                    'type': 'UI'
                }
            }).then(res => {
                app.log('==>>POST res:' + res)
                let url = JSON.parse(res.data).data.fileUrl
                app.log(url)
                checkStatus(res)
                resolve(url)
            }).catch(err => {
            }).finally(() => {
                app.log('==>>文件上传 POST:' + uri)
            })
        })

    })
}

function postReqGetBuffer(uri, data) {

    return new Promise(function (resolve, reject) {
        getHeader(uri).then(res => {
            wx.pro.request({
                url: apiHost + uri,
                method: 'GET',
                header: res,
                responseType: 'arraybuffer', //此处是请求文件流，必须带入的属性
            }).then(res => {
                app.log('==>>GET res:' + res)
                checkStatus(res)
                resolve(res)
            }).catch(err => {
                app.log('==>>GET res:' + err)
                reject(err)
            }).finally(() => {
                app.log('==>>excle导出 GET:' + uri)
            })
        })
    })
}


//===========================================公用方法===========================

function checkToken() {
    let b = app.globalData.head.hasToken
    app.log('==>>api--checkToken:::'+b)
    return new Promise(function (resolve, reject) {
        resolve(b)
    })
}

function get(uri) {
    app.log('==>>GET 请求参数')
    app.log(uri)

    return new Promise(function (resolve, reject) {
        getHeader(uri).then(res => {
            wx.pro.request({
                url: apiHost + uri,
                method: 'GET',
                header: res,
            }).then(res => {
                app.log('==>>GET res:' + res)
                app.log(res)
                checkStatus(res)
                resolve(res)
            }).catch(err => {
                app.log('==>>GET err:' + err)
                reject(err)
            }).finally(() => {
                app.log('==>>GET:final:' + uri)
            })
        })
    })

}

function post(uri, data) {
    app.log('==>>POST 请求参数')
    app.log(data)

    return new Promise(function (resolve, reject) {
        getHeader(uri).then(res => {
            wx.pro.request({
                url: apiHost + uri,
                method: 'POST',
                data: data,
                header: res,
            }).then(res => {
                app.log('==>>POST res:' + res)
                checkStatus(res)
                resolve(res)
            }).catch(err => {
                app.log('==>>POST err:' + err)
                reject(err)
            }).finally(() => {
                app.log('==>>POST:final:' + uri)
            })
        })
    })

}

function put(uri, data) {
    app.log('==>>PUT 请求参数')
    app.log(data)


    return new Promise(function (resolve, reject) {
        getHeader(uri).then(res => {
            wx.pro.request({
                url: apiHost + uri,
                method: 'PUT',
                data: data,
                header: res,
            }).then(res => {
                app.log('==>>PUT res:' + res)
                checkStatus(res)
                resolve(res)
            }).catch(err => {
                app.log('==>>PUT err:' + err)
                reject(err)
            }).finally(() => {
                app.log('==>>PUT:final:' + uri)
            })
        })
    })


}


function del(uri) {
    app.log('==>>DELETE 请求参数')
    app.log(uri)


    return new Promise(function (resolve, reject) {
        getHeader(uri).then(res => {
            wx.pro.request({
                url: apiHost + uri,
                method: 'DELETE',
                header: res,
            }).then(res => {
                app.log('==>>DELETE res:' + res)
                checkStatus(res)
                resolve(res)
            }).catch(err => {
                app.log('==>>DELETE err:' + err)
                reject(err)
            }).finally(() => {
                app.log('==>>DELETE:final:' + uri)
            })
        })
    })


}


function getHeader(uri) {
    var header = {
        'content-type': 'application/json'
    }
    if (exceptionAddrArr.indexOf(uri) == -1) { //排除请求的地址不需要token的地址
        // header.openid = app.globalData.head.openid;
        header.token = app.globalData.head.token

    }
    return new Promise(function (resolve, reject) {
        app.log('====header')
        app.log(header)
        resolve(header)
    })

}

/**
 * @param {Object} sStr
 * 对字符串编码
 */
function URLencode(sStr) {
    return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g, '%22').replace(/\'/g, '%27').replace(/\//g, '%2F');
}

let t_num = 0
let e_num = 0

function checkStatus(res) {
    app.log('==========>>checkStatus')
    app.log(res)
    if (res.statusCode == 401 || res.data.code == 401) {
        app.log('====>>token过期')
        app.globalData.head.token = ''
        if (t_num < 2) {
            t_num++
            wx.showModal({
                title: '身份认证过期,点击确定重新登录',
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        app.log('====>>token过期，用户点击确定')
                        login()
                        t_num--
                    } else if (res.cancel) {
                        app.log('====>>token过期，用户点击取消')
                    }

                }
            })
        }
    } else if (res.statusCode == 403 ){
        wx.showModal({
            title: '拒绝访问，请联系管理人员',
            showCancel: false,
            success(res) {
                if (res.confirm) {
                    app.log('====>>token过期，用户点击确定')
                } else if (res.cancel) {
                    app.log('====>>token过期，用户点击取消')
                }
            }
        })
    }

    else if (res.statusCode >= 500 && res.statusCode < 600) {
        wx.showModal({
            title: '服务异常',
            showCancel: false,
            success(res) {
                if (res.confirm) {
                    app.log('====>>服务器异常，用户点击确定')
                } else if (res.cancel) {
                    app.log('====>>服务器异常，用户点击取消')
                }
            }
        })
    }
    else if (res.data.code == 1000) {
        wx.showModal({
            title: res.data.msg,
            showCancel: false,
            success(res) {
                if (res.confirm) {
                    app.log('====>>处理失败，用户点击确定')
                } else if (res.cancel) {
                    app.log('====>>处理失败，用户点击取消')
                }
            }
        })
    }
}


// ================================ 尿机 =====================================
//保存数据
function saveUi(data) {
    let uri = '/s-xcx/api/v6/urine/addUi'
    return new Promise(function (resolve, reject) {
        post(uri, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })

}

function getUiReport(data) {
    let uri = '/s-xcx/api/v6/urine/getUiReport'

    return new Promise(function (resolve, reject) {
        post(uri, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

function getNewUiRet(data) {

    let uri = '/s-xcx/api/v6/urine/getNewUiRet'
    return new Promise(function (resolve, reject) {
        post(uri,data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

function findUiByPager(data) {
    let uri = '/s-xcx/api/v6/urine/findUiByPager'
    return new Promise(function (resolve, reject) {
        post(uri, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })

}

function exPortUis(data) {
    let uri = '/s-xcx/api/v6/urine/exPortUis'
    return new Promise(function (resolve, reject) {
        postReqGetBuffer(uri, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

/*================= 用户信息 管理  start===================*/


function getCode(phone) {
    let userName = 'A' + phone
    let uri = '/s-user/api/v2/user/getCode?userName=' + userName

    return new Promise(function (resolve, reject) {
        get(uri).then(res => {
            resolve(true)
        }).catch(err => {
            reject(false)
        })
    })

}

function findAllInfos() {
    let uri = '/s-xcx/api/v3/ex/info/findAllInfos'
    return new Promise(function (resolve, reject) {
        get(uri).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

function addFriend(data) {
    let uri = '/s-xcx/api/v3/ex/info/bindFriend'
    return new Promise(function (resolve, reject) {
        post(uri, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

function updInfo(data) {
    let uri = '/s-xcx/api/v3/ex/info/updInfo'
    return new Promise(function (resolve, reject) {
        put(uri, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

function delFriend(friendId) {
    let uri = '/s-xcx/api/v3/ex/info/delFriend?friendId=' + friendId
    return new Promise(function (resolve, reject) {
        del(uri).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}


/*================= 用户信息 管理  end===================*/
